/**
 * 设备评价控制器模块
 * controller/deviceFeedback.js
 */

const util = require("../common/util");
const DeviceFeedbackDB = require("../model/sqlite/deviceFeedback");

/**
 * 获取设备评价列表
 * @param {express.Request} req
 * @param {express.Response} res
 */
async function getFeedbackList(req, res) {
  try {
    const deviceId = req.params.deviceId;
    const limit = req.query.limit ? parseInt(req.query.limit) : -1;
    const offset = req.query.offset ? parseInt(req.query.offset) : -1;

    console.log('Getting feedback for device:', deviceId);
    console.log('Limit:', limit, 'Offset:', offset);

    let db = DeviceFeedbackDB.getInstance();
    await db.connect();
    
    const feedback = await db.getFeedbackList(deviceId, limit, offset);
    console.log('Feedback data:', feedback);
    
    res.status(200).json({
      code: 200,
      msg: "获取设备评价成功",
      data: feedback,
      timestamp: Date.now()
    });
  } catch (err) {
    console.error('获取设备评价失败:', err);
    res.status(500).json({
      code: 500,
      msg: "获取设备评价失败",
      data: null
    });
  }
}

/**
 * 获取设备平均评分
 * @param {express.Request} req
 * @param {express.Response} res
 */
async function getAverageRating(req, res) {
  try {
    const deviceId = req.params.deviceId;
    console.log('Getting average rating for device:', deviceId);
    
    let db = DeviceFeedbackDB.getInstance();
    await db.connect();
    
    const rating = await db.getAverageRating(deviceId);
    console.log('Rating data:', rating);
    
    res.status(200).json({
      code: 200,
      msg: "获取设备评分成功",
      data: rating,
      timestamp: Date.now()
    });
  } catch (err) {
    console.error('获取设备评分失败:', err);
    res.status(500).json({
      code: 500,
      msg: "获取设备评分失败",
      data: null
    });
  }
}

/**
 * 添加设备评价
 * @param {express.Request} req
 * @param {express.Response} res
 */
async function addFeedback(req, res) {
  try {
    const deviceId = req.params.deviceId;
    console.log('Session user:', req.session.user);
    console.log('Request user:', req.user);
    
    if (!req.user || !req.user.id) {
      return res.status(401).json({
        code: 401,
        msg: "用户未登录或会话已过期",
        data: null
      });
    }

    const userId = req.user.id;
    const { rating, feedback } = req.body;

    console.log('Adding feedback:', { deviceId, userId, rating, feedback });

    // 参数验证
    if (!rating || rating < 1 || rating > 5) {
      return res.status(400).json({
        code: 400,
        msg: "评分必须在1-5之间",
        data: null
      });
    }

    if (!feedback || feedback.trim().length === 0) {
      return res.status(400).json({
        code: 400,
        msg: "评价内容不能为空",
        data: null
      });
    }

    let db = DeviceFeedbackDB.getInstance();
    await db.connect();
    
    const result = await db.addFeedback(deviceId, userId, rating, feedback);
    console.log('Add feedback result:', result);
    
    res.json({
      code: 200,
      msg: "添加评价成功",
      data: { id: result }
    });
  } catch (err) {
    console.error('添加设备评价失败:', err);
    res.status(500).json({
      code: 500,
      msg: "添加设备评价失败",
      data: null
    });
  }
}

/**
 * 点赞评价
 * @param {express.Request} req
 * @param {express.Response} res
 */
async function likeFeedback(req, res) {
  try {
    const feedbackId = req.params.feedbackId;
    const userId = req.user.id;

    console.log('Liking feedback:', { feedbackId, userId });

    let db = DeviceFeedbackDB.getInstance();
    await db.connect();
    
    const result = await db.likeFeedback(feedbackId, userId);
    console.log('Like result:', result);
    
    res.status(200).json({
      code: 200,
      msg: result ? "点赞成功" : "取消点赞成功",
      data: { liked: result },
      timestamp: Date.now()
    });
  } catch (err) {
    console.error('点赞失败:', err);
    res.status(500).json({
      code: 500,
      msg: "点赞失败",
      data: null
    });
  }
}

/**
 * 踩评价
 * @param {express.Request} req
 * @param {express.Response} res
 */
async function dislikeFeedback(req, res) {
  try {
    const feedbackId = req.params.feedbackId;
    const userId = req.user.id;

    console.log('Disliking feedback:', { feedbackId, userId });

    let db = DeviceFeedbackDB.getInstance();
    await db.connect();
    
    const result = await db.dislikeFeedback(feedbackId, userId);
    console.log('Dislike result:', result);
    
    res.status(200).json({
      code: 200,
      msg: result ? "踩成功" : "取消踩成功",
      data: { disliked: result },
      timestamp: Date.now()
    });
  } catch (err) {
    console.error('踩失败:', err);
    res.status(500).json({
      code: 500,
      msg: "踩失败",
      data: null
    });
  }
}

/**
 * 获取所有设备评价列表 (管理员)
 * @param {express.Request} req
 * @param {express.Response} res
 */
async function getAdminFeedbackList(req, res) {
  try {
    const limit = req.query.limit ? parseInt(req.query.limit) : 10;
    const offset = req.query.offset ? parseInt(req.query.offset) : 0;
    const orderBy = req.query.orderBy || 'created_time';
    const sort = req.query.sort || 'desc';

    let db = DeviceFeedbackDB.getInstance();
    await db.connect();

    const feedbackList = await db.getAllFeedbackWithDeviceInfo(limit, offset, orderBy, sort);
    const total = await db.getAllFeedbackCount();

    res.status(200).json({
      code: 200,
      msg: "获取所有设备评价成功",
      data: {
        list: feedbackList,
        total: total
      },
      timestamp: Date.now()
    });

  } catch (err) {
    console.error('获取所有设备评价列表失败:', err);
    res.status(500).json({
      code: 500,
      msg: "获取所有设备评价列表失败",
      data: null
    });
  }
}

/**
 * 更新设备评价
 * @param {express.Request} req
 * @param {express.Response} res
 */
async function updateFeedback(req, res) {
  try {
    const feedbackId = req.params.feedbackId;
    const { feedback, rating } = req.body;

    if (!req.user || !req.user.id) {
      return res.status(401).json({
        code: 401,
        msg: "用户未登录或会话已过期",
        data: null
      });
    }

    if (!feedback || feedback.trim().length === 0) {
      return res.status(400).json({
        code: 400,
        msg: "评价内容不能为空",
        data: null
      });
    }
    if (rating === undefined || rating < 1 || rating > 5) {
      return res.status(400).json({
        code: 400,
        msg: "评分必须在1-5之间",
        data: null
      });
    }

    let db = DeviceFeedbackDB.getInstance();
    await db.connect();

    // 验证评论是否属于当前用户
    const existingFeedback = await db.getFeedbackById(feedbackId);
    if (!existingFeedback) {
      return res.status(404).json({ code: 404, msg: "评论不存在" });
    }
    if (existingFeedback.user_id !== req.user.id) {
      return res.status(403).json({ code: 403, msg: "无权编辑此评论" });
    }

    const result = await db.updateFeedback(feedbackId, feedback, rating);

    if (result) {
      res.status(200).json({
        code: 200,
        msg: "评价更新成功",
        data: null
      });
    } else {
      res.status(500).json({
        code: 500,
        msg: "评价更新失败",
        data: null
      });
    }
  } catch (err) {
    console.error('更新设备评价失败:', err);
    res.status(500).json({
      code: 500,
      msg: "更新设备评价失败",
      data: null
    });
  }
}

/**
 * 删除设备评价
 * @param {express.Request} req
 * @param {express.Response} res
 */
async function deleteFeedback(req, res) {
  try {
    const feedbackId = req.params.feedbackId;
    const userId = req.user.id;
    const isAdminRoute = req.path.startsWith('/admin/');
    const isAdmin = req.user.role === 1;

    if (!req.user || !userId) {
      return res.status(401).json({
        code: 401,
        msg: "用户未登录或会话已过期",
        data: null
      });
    }

    let db = DeviceFeedbackDB.getInstance();
    await db.connect();

    const existingFeedback = await db.getFeedbackById(feedbackId);
    if (!existingFeedback) {
      return res.status(404).json({ code: 404, msg: "评论不存在" });
    }

    // 如果是管理员路由，只检查管理员权限
    if (isAdminRoute) {
      if (!isAdmin) {
        return res.status(403).json({ code: 403, msg: "需要管理员权限" });
      }
    } else {
      // 普通用户路由，检查是否是评论作者或管理员
      if (existingFeedback.user_id !== userId && !isAdmin) {
        return res.status(403).json({ code: 403, msg: "无权删除此评论" });
      }
    }

    const result = await db.deleteReview(feedbackId);

    if (result) {
      res.status(200).json({
        code: 200,
        msg: "评论删除成功",
        data: null
      });
    } else {
      res.status(500).json({
        code: 500,
        msg: "评论删除失败",
        data: null
      });
    }

  } catch (err) {
    console.error('删除设备评价失败:', err);
    res.status(500).json({
      code: 500,
      msg: "删除设备评价失败",
      data: null
    });
  }
}

/**
 * 获取指定用户的评论信息
 * @param {express.Request} req
 * @param {express.Response} res
 */
async function getUserFeedback(req, res) {
  try {
    const userId = parseInt(req.params.userId);
    const limit = req.query.limit ? parseInt(req.query.limit) : 10;
    const offset = req.query.offset ? parseInt(req.query.offset) : 0;

    if (!req.user || !req.user.id) {
      return res.status(401).json({
        code: 401,
        msg: "用户未登录或会话已过期",
        data: null
      });
    }

    // 只允许用户查看自己的评论或管理员查看任何用户的评论
    if (req.user.id !== userId && !req.user.isAdmin) {
      return res.status(403).json({
        code: 403,
        msg: "无权查看其他用户的评论",
        data: null
      });
    }

    let db = DeviceFeedbackDB.getInstance();
    await db.connect();

    const feedbackList = await db.getUserFeedback(userId, limit, offset);
    const total = await db.getUserFeedbackCount(userId);

    res.status(200).json({
      code: 200,
      msg: "获取用户评论成功",
      data: {
        list: feedbackList,
        total: total
      },
      timestamp: Date.now()
    });

  } catch (err) {
    console.error('获取用户评论失败:', err);
    res.status(500).json({
      code: 500,
      msg: "获取用户评论失败",
      data: null
    });
  }
}

module.exports = {
  getFeedbackList,
  getAverageRating,
  addFeedback,
  likeFeedback,
  dislikeFeedback,
  getAdminFeedbackList,
  updateFeedback,
  deleteFeedback,
  getUserFeedback
}; 